package com.chat.net.socket;

import com.chat.entity.DataPackage;
import com.chat.entity.event.ChannelEvent;

import java.util.HashMap;
import java.util.Map;

/**
 * 事件驱动
 */
public class EventHandlerDrive implements ChannelHandler {
    //数据流事件 双头栈结构
    public static Map<Integer, ChannelEvent> events = new HashMap<>();
    public EventHandlerDrive() {
    }

    //处理Channel事件
    @Override
    public Object handler(Channel ctx, Object msg) {
        System.out.println("开始处理事件驱动!");
        if(msg instanceof DataPackage){
            DataPackage dataPackage = (DataPackage) msg;
            System.out.println(dataPackage.toString());
            //触发事件监听
            ChannelEvent event = events.remove(dataPackage.getEventId());
            if(event != null){
                event.onChannelEvent(ctx,dataPackage);
            }
            return dataPackage;
        }
        return null;
    }

    public void addEvent(ChannelEvent event) {
        events.put(event.getId(),event);
    }


}
